/* eslint-disable react-hooks/exhaustive-deps */
import React, { useState, useRef, useEffect } from 'react';
import {
  Breadcrumb,
  Button,
  Card,
  Form,
  Input,
  Radio,
  Space,
  message,
  Modal,
  Upload,
} from 'antd';

import { baseURL } from 'utils/request';
import { getToken } from 'utils/storage';
import { UploadOutlined } from '@ant-design/icons';

import { Link } from 'react-router-dom';

import Channel from 'components/Channel';

import ReactQuill from 'react-quill';
import 'react-quill/dist/quill.snow.css';

import styles from './index.module.scss';

import {
  publishArticleAPI,
  getArticleByIdAPI,
  updateArticleAPI,
} from 'api/articles';

export default function ArticlePublish(_props) {
  const [type, setType] = useState(1);
  const [imgSrc, setImgSrc] = useState('');
  const [fileList, setFileList] = useState([]);
  const draftRef = useRef(false);
  const formRef = useRef({});
  const props = {
    name: 'image',
    accept: '.png,.jpg',
    action: `${baseURL}/v1_0/upload`,
    headers: {
      authorization: `Bearer ${getToken()}`,
    },
    onChange(info) {
      setFileList(info.fileList);
      if (info.file.status === 'done') {
        message.success(`${info.file.name} 上传成功`);
      } else if (info.file.status === 'error') {
        message.error(`${info.file.name} 上传失败`);
      }
    },
    onPreview(file) {
      setImgSrc(file.thumbUrl || file.url);
    },
    beforeUpload(file) {
      const imgs = ['image/jpg', 'image/png'];

      if (!imgs.includes(file.type)) {
        message.warning('不允许上传的文件类型');
        return Upload.LIST_IGNORE;
      }
    },
  };
  // 获取编辑时传过来的id
  const articleId = _props.match.params.id;
  console.log(articleId);
  const loadArticleById = async (id) => {
    const res = await getArticleByIdAPI(id);

    formRef.current.setFieldsValue({ ...res.data, type: res.data.cover.type });

    setType(res.data.cover.type);

    setFileList(res.data.cover.images.map((item) => ({ url: item })));
    console.log(res);
  };
  useEffect(() => {
    if (articleId) {
      loadArticleById(articleId);
    }
  }, []);
  const handleFinish = async (values) => {
    if (showFilelist.length !== type) {
      return message.warning('图片数量不对');
    }
    let formData = {
      ...values,
    };
    formData.cover = {
      type: values.type,
      images: articleId
        ? showFilelist.map((item) =>
            item.response ? item.response.data.url : item.url
          )
        : showFilelist.map((item) => item.response.data.url),
    };
    delete formData.type;
    if (articleId) {
      await updateArticleAPI(articleId, formData, draftRef.current);
      message.success('编辑成功', 1);
    } else {
      await publishArticleAPI(formData, draftRef.current);
      message.success('发布成功', 1);
    }

    _props.history.push('/list');

    console.log(formData);
  };
  const handleValuesChange = (changeValues, allValue) => {
    if (changeValues.type !== undefined) {
      setType(changeValues.type);
    }
  };
  const showFilelist = fileList.filter((item, index) => {
    if (type === 0) return false;
    if (type === 1) return index === 0;
    return true;
  });
  return (
    <div className={styles.root}>
      <Card
        title={
          <Breadcrumb>
            <Breadcrumb.Item>
              <Link to="/home">首页</Link>
            </Breadcrumb.Item>
            <Breadcrumb.Item>
              {`${articleId ? '编辑' : '发布'}`}文章
            </Breadcrumb.Item>
          </Breadcrumb>
        }
      >
        <Form
          ref={formRef}
          onFinish={handleFinish}
          name="basic"
          labelCol={{ span: 4 }}
          wrapperCol={{ span: 20 }}
          size="large"
          autoComplete="off"
          initialValues={{
            content: '',
            type: 1,
          }}
          onValuesChange={handleValuesChange}
        >
          <Form.Item
            label="标题"
            name="title"
            rules={[
              {
                required: true,
                message: '请输入文章标题',
              },
            ]}
          >
            <Input placeholder="请输入文章标题" />
          </Form.Item>
          <Form.Item
            label="频道"
            name="channel_id"
            rules={[
              {
                required: true,
                message: '请选择频道',
              },
            ]}
          >
            <Channel allowClear></Channel>
          </Form.Item>
          <Form.Item
            label="内容"
            name="content"
            rules={[
              {
                required: true,
                message: '文章内容不能为空',
                validator: (_, value) => {
                  if (value === '<p><br></p>' || !value) {
                    return Promise.reject(new Error('内容不能为空'));
                  }
                  return Promise.resolve();
                },
              },
            ]}
          >
            <ReactQuill
              theme="snow"
              placeholder="请输入文章内容..."
            ></ReactQuill>
          </Form.Item>
          <Form.Item label="封面" name="type">
            <Radio.Group>
              <Radio value={1}>单图</Radio>
              <Radio value={3}>三图</Radio>
              <Radio value={0}>无图</Radio>
            </Radio.Group>
          </Form.Item>
          <Form.Item wrapperCol={{ offset: 4 }} name="test">
            <Upload {...props} listType="picture-card" fileList={showFilelist}>
              {fileList.length < type && <UploadOutlined />}
            </Upload>
          </Form.Item>
          <Form.Item wrapperCol={{ offset: 4 }}>
            <Space>
              <Button type="primary" htmlType="submit">
                {`${articleId ? '编辑' : '发布'}`}文章
              </Button>
              <Button
                type="primary"
                htmlType="submit"
                onClick={() => (draftRef.current = true)}
              >
                存草稿
              </Button>
            </Space>
          </Form.Item>
        </Form>
      </Card>
      <Modal
        title="预览图片"
        visible={!!imgSrc}
        footer={null}
        onCancel={() => setImgSrc('')}
      >
        <img width={480} style={{ objectFit: 'cover' }} src={imgSrc} alt="" />
      </Modal>
    </div>
  );
}
